package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.pojo.PlayRecord;
import com.zhentao.service.PlayRecordService;
import com.zhentao.mapper.PlayRecordMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* @author lenovo
* @description 针对表【play_record(播放记录表)】的数据库操作Service实现
* @createDate 2025-10-14 09:53:42
*/
@Service
public class PlayRecordServiceImpl extends ServiceImpl<PlayRecordMapper, PlayRecord>
    implements PlayRecordService{

    @Override
    @Transactional(rollbackFor = Exception.class)
    public PlayRecord saveOrUpdateRecord(Long userId, Long contentId, Long chapterId, Integer progress) {
        // 先尝试更新
        LambdaUpdateWrapper<PlayRecord> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(PlayRecord::getUserId, userId)
                    .eq(PlayRecord::getChapterId, chapterId)
                    .set(PlayRecord::getProgress, progress)
                    .set(PlayRecord::getLastPlayTime, new Date())
                    .set(PlayRecord::getContentId, contentId); // 确保 contentId 也是最新的
        
        boolean updated = this.update(updateWrapper);
        
        if (updated) {
            // 更新成功，查询并返回
            LambdaQueryWrapper<PlayRecord> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PlayRecord::getUserId, userId)
                       .eq(PlayRecord::getChapterId, chapterId);
            return this.getOne(queryWrapper);
        } else {
            // 更新失败，说明记录不存在，创建新记录
            try {
                PlayRecord newRecord = new PlayRecord();
                newRecord.setUserId(userId);
                newRecord.setContentId(contentId);
                newRecord.setChapterId(chapterId);
                newRecord.setProgress(progress);
                newRecord.setLastPlayTime(new Date());
                newRecord.setCreateTime(new Date());
                this.save(newRecord);
                return newRecord;
            } catch (Exception e) {
                // 如果插入失败（可能是并发导致的重复），再次尝试更新
                this.update(updateWrapper);
                LambdaQueryWrapper<PlayRecord> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(PlayRecord::getUserId, userId)
                           .eq(PlayRecord::getChapterId, chapterId);
                return this.getOne(queryWrapper);
            }
        }
    }

    @Override
    public List<PlayRecord> getUserPlayRecords(Long userId) {
        LambdaQueryWrapper<PlayRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlayRecord::getUserId, userId)
                    .orderByDesc(PlayRecord::getLastPlayTime);
        return this.list(queryWrapper);
    }

    @Override
    public PlayRecord getPlayRecordByUserAndContent(Long userId, Long contentId) {
        LambdaQueryWrapper<PlayRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlayRecord::getUserId, userId)
                    .eq(PlayRecord::getContentId, contentId)
                    .orderByDesc(PlayRecord::getLastPlayTime)
                    .last("LIMIT 1");
        return this.getOne(queryWrapper);
    }

    @Override
    public PlayRecord getPlayRecordByUserAndChapter(Long userId, Long chapterId) {
        LambdaQueryWrapper<PlayRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlayRecord::getUserId, userId)
                    .eq(PlayRecord::getChapterId, chapterId);
        return this.getOne(queryWrapper);
    }

    @Override
    public boolean deletePlayRecord(Long userId, Long contentId) {
        LambdaQueryWrapper<PlayRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PlayRecord::getUserId, userId)
                    .eq(PlayRecord::getContentId, contentId);
        
        // 先查询要删除的记录数量，用于日志记录
        int count = (int) this.count(queryWrapper);
        System.out.println("准备删除播放记录，userId: " + userId + ", contentId: " + contentId + ", 记录数量: " + count);
        
        boolean result = this.remove(queryWrapper);
        System.out.println("删除播放记录结果: " + result);
        
        return result;
    }
}




